/**
 * Copyright (C) 2016 Eshore Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.eshore.thrpc.heartbeat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.thrift.TServiceClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eshore.thrpc.common.ServerNode;

/**
 * 
 * 心跳检测服务端
 * 
 * 
 * @author zhouzhixiang
 * @date 2016年12月20日 下午5:53:51
 * @since 1.0
 */
public class HeartBeatTask<T> implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatTask.class);

    private final ServerNode serverNode;
    
    private Socket socket;

    /** 连接池 */
    private final GenericKeyedObjectPool<ServerNode, TServiceClient> pool;

    /**
     * 
     * <p>
     *
     */
    HeartBeatTask(ServerNode serverNode, GenericKeyedObjectPool<ServerNode, TServiceClient> pool) {
        this.serverNode = serverNode;
        this.pool = pool;
    }

    @Override
    public void run() {
        try {
            boolean isValid = false;
            isValid = checkSocket(serverNode);

            if (!isValid) {
                int count = pool.getNumActive() + pool.getNumIdle();
                if (count > 0) {
                    pool.clear();
                }
            }
        } catch (Exception t) {
            pool.clear();
            LOGGER.warn("Exception when heartbeat to server:{} ", serverNode.genAddress(), t);
        }

    }

    /**
     * 检查socket是否正常
     * <p>
     * 
     * @param serverNode
     * @throws Exception
     */
    private boolean checkSocket(ServerNode serverNode) {
        try {
            if(socket !=null && socket.isConnected()){
                socket.sendUrgentData(0xFF);
            }else{
                socket = new Socket();
                SocketAddress endpoint = new InetSocketAddress(serverNode.getIp(), serverNode.getPort()) ;
                socket.connect(endpoint );
                socket.sendUrgentData(0xFF);
            }
        } catch (IOException e) {
            LOGGER.error("server:{} may be shutdown!!!",serverNode.getName(), e);
            try {
                socket.close();
                socket = null;
            } catch (IOException e1) {
            }
            return false;
        }
        return true;
    }

}
